package cn.itlaobing.springmvc.web.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.itlaobing.springmvc.entity.Account;
import cn.itlaobing.springmvc.service.AccountService;

/**
 * 登录   退出
 * @author classA-43
 *
 */
@Controller
public class SessionController {
	public static final String CURRENT_ACCOUNT="currentAccount";
	
	@Autowired
    private AccountService accountService;
	
	@RequestMapping(value="/signIn",method=RequestMethod.GET)
	public String signIn(){
		return "signIn";
	}
	
	//登录
	@RequestMapping(value="/signIn",method=RequestMethod.POST)
	public String signIn(HttpSession session,Model model, String account,String password){
		Account accout =accountService.validate(account, password);
		if(accout!=null){
			session.setAttribute(CURRENT_ACCOUNT, accout);
			//更新最后一次登录时间
			accountService.updateLastSignInDateTime(accout.getAccount());
			return "redirect:/home";
		}else{
			model.addAttribute("signInError", "用户名或者密码错误");
			return "signIn";
		}
		
	}
	//登出
	@RequestMapping(value="/signOut",method=RequestMethod.GET)
	public String signOut(HttpSession session){
		
		//让session失效
		session.invalidate();
		return "redirect:/signIn";
	}
}
